using AutoMapper;
using B.S.NewMedical.Api.Read.Application.Command.ContentManagement.Hospital;
using B.S.NewMedical.Api.Read.DTOS.Hospital;
using B.S.NewMedical.Api.Read.DTOS.Department;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using B.S.NewMedical.Domain.Hospital;
using B.S.NewMedical.Domain.Doctor;

namespace B.S.NewMedical.Api.Read.Application.Handler.ContentManagement.Hospital
{
    /// <summary>
    /// 根据ID获取医院详情处理器
    /// </summary>
    public class GetHospitalByIdHandler : IRequestHandler<GetHospitalByIdCommand, ApiResult<HospitalDto>>
    {
        private readonly IBaseRepository<HospitalModel> _hospitalRepository;
        private readonly IBaseRepository<HospitalDepartmentModel> _hospitalDepartmentRepository;
        private readonly IBaseRepository<DepartmentModel> _departmentRepository;
        private readonly IBaseRepository<HospitalTypeModel> _hospitalTypeRepository;
        private readonly ILogger<GetHospitalByIdHandler> _logger;
        private readonly IMapper _mapper;

        public GetHospitalByIdHandler(
            IBaseRepository<HospitalModel> hospitalRepository,
            IBaseRepository<HospitalDepartmentModel> hospitalDepartmentRepository,
            IBaseRepository<DepartmentModel> departmentRepository,
            IBaseRepository<HospitalTypeModel> hospitalTypeRepository,
            ILogger<GetHospitalByIdHandler> logger,
            IMapper mapper)
        {
            _hospitalRepository = hospitalRepository ?? throw new ArgumentNullException(nameof(hospitalRepository));
            _hospitalDepartmentRepository = hospitalDepartmentRepository ?? throw new ArgumentNullException(nameof(hospitalDepartmentRepository));
            _departmentRepository = departmentRepository ?? throw new ArgumentNullException(nameof(departmentRepository));
            _hospitalTypeRepository = hospitalTypeRepository ?? throw new ArgumentNullException(nameof(hospitalTypeRepository));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
            _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
        }

        /// <summary>
        /// 处理根据ID获取医院详情请求
        /// </summary>
        public async Task<ApiResult<HospitalDto>> Handle(GetHospitalByIdCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始查询医院详情，医院ID：{HospitalId}", request.HospitalId);

                // 查询医院信息
                var hospital = await _hospitalRepository.GetValue(request.HospitalId);

                if (hospital == null || hospital.IsDeleted)
                {
                    _logger.LogWarning("医院不存在或已被删除，医院ID：{HospitalId}", request.HospitalId);
                    return new ApiResult<HospitalDto>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "医院不存在或已被删除"
                    };
                }

                // 查询医院科室关联信息
                var hospitalDepartments = await _hospitalDepartmentRepository.GetAll()
                    .Where(hd => !hd.IsDeleted && hd.HospitalId == request.HospitalId)
                    .ToListAsync(cancellationToken);

                // 获取科室ID列表
                var departmentIds = hospitalDepartments.Select(hd => hd.DepartmentId).ToList();

                // 查询科室信息
                var departments = new List<DepartmentModel>();
                if (departmentIds.Any())
                {
                    departments = await _departmentRepository.GetAll()
                        .Where(d => !d.IsDeleted && departmentIds.Contains(d.Id))
                        .ToListAsync(cancellationToken);
                }

                // 获取医院类型信息
                string? hospitalTypeName = null;
                if (hospital.HospitalTypeId.HasValue)
                {
                    try
                    {
                        var hospitalType = await _hospitalTypeRepository.GetValue(hospital.HospitalTypeId.Value);
                        hospitalTypeName = hospitalType?.HospitalType;
                    }
                    catch (Exception ex)
                    {
                        _logger.LogWarning(ex, "查询医院类型信息失败，医院类型ID：{HospitalTypeId}", hospital.HospitalTypeId.Value);
                    }
                }

                // 映射医院数据
                var hospitalDto = _mapper.Map<HospitalDto>(hospital);
                hospitalDto.HospitalTypeName = hospitalTypeName;

                // 映射科室信息
                hospitalDto.DepartmentSetup = _mapper.Map<List<DepartmentDto>>(departments);

                _logger.LogInformation("查询医院详情成功，医院名称：{HospitalName}，科室数量：{DepartmentCount}", 
                    hospitalDto.HospitalName, hospitalDto.DepartmentSetup.Count);

                return new ApiResult<HospitalDto>
                {
                    Code = ApiEnum.Success,
                    Msg = "查询成功",
                    Data = hospitalDto
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询医院详情时发生错误，医院ID：{HospitalId}", request.HospitalId);
                return new ApiResult<HospitalDto>
                {
                    Code = ApiEnum.Error,
                    Msg = "查询失败：" + ex.Message
                };
            }
        }
    }
}